// 用户注册
import bcrypt from "bcrypt";
import { userSignupSchema } from "@/validators/user";

export default defineEventHandler(async (event) => {
  // 校验参数
  const result = await runValidate(userSignupSchema, event);
  // 获取运行时  nuxt.config.ts 中的配置
  const config = useRuntimeConfig();
  const { account, password } = result.data;
  // 校验账号是否已存在
  const user = await UserSchema.findOne({ account: account }).lean();
  if (user) {
    throw createError({
      statusCode: 409,
      statusMessage: "该账号已经被注册，请直接登录",
    });
  }
  // 加密密码
  const hash = await bcrypt.hash(password, config.bcrypt.saltRounds);
  const userCreatedData = { account: account, password: hash };
  // 创建用户
  const newUser = await UserSchema.create(userCreatedData);
  return newUser;
});
